package com.example.demo.algorithm.sort;

/**
 * @Description: 冒泡排序，最大的元素沉淀在最后面  时间复杂度O(N²)
 * @Author: xiatian
 * @CreateTime: 2021/9/7
 * @Company: kangxu
 */
public class Bubble {
    public static void sort(Comparable[] a) {
        for (int i = a.length - 1; i > 0; i--) {
            for (int j = 0; j < i; j++) {
                //比较j和j+1的值
                if (greater(a[j], a[j + 1])) {
                    exch(a, j, j + 1);
                }
            }
        }
    }

    public static boolean greater(Comparable v, Comparable w) {
        return v.compareTo(w) > 0;
    }

    /**
     * 交换数组中，索引i和j的值
     *
     * @param a
     * @param i
     * @param j
     */
    public static void exch(Comparable[] a, int i, int j) {
        Comparable temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }

}
